package com.mj.haier.rrskx.sharding;

import java.util.*;

import com.alibaba.fastjson.JSON;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.shardingsphere.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

public class PreciseTradeShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    private final Logger log = LoggerFactory.getLogger(PreciseTradeShardingAlgorithm.class);


    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        log.debug("availableTargetNames: {}", JSON.toJSONString(availableTargetNames));
        log.debug("shardingValue: {}", JSON.toJSONString(shardingValue.getValue()));
        log.debug("对应的rrskxClient值: {}", JSON.toJSONString(TradeUtil.getTradeShardingMap().getOrDefault(shardingValue.getValue(), "_default")));
        List<String> shardingResults = new ArrayList<>();
        availableTargetNames.forEach(targetName -> {

            String suffix = targetName.substring(targetName.lastIndexOf("_"));
            if(StringUtils.isNoneBlank(suffix)
                && suffix.equals(TradeUtil.getTradeShardingMap().getOrDefault(shardingValue.getValue(), "_default"))){
                shardingResults.add(targetName);
            }
        });

        return shardingResults.get(0);
    }
}
